import styles from './index.module.scss'
import { addFile, editProfile, getUserEdit } from '@/store/actions/profile'
import React, { useEffect, useRef, useState } from 'react'
import NavBar from '@/components/nav-bar'
import { List, DatePicker, Drawer, Toast, Modal } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import classNames from 'classnames'
import EditInput from './components/EditInput'
import EditList from './components/EditList'
import dayjs from 'dayjs'
import { loginOut } from '@/store/actions/login'
import { useHistory } from 'react-router'
const { Item } = List

export default function Edit() {
  const dispatch = useDispatch()
  const histroy = useHistory()
  const [open, setOpen] = useState({
    visible: false,
    type: '',
  })
  const [listOpen, setListOpen] = useState({
    visible: false,
    type: '',
  })
  const onLeftClick = () => {
    // 关闭昵称简介
    setOpen({
      visible: false,
      type: '',
    })
    // 关闭头像性别
    setListOpen({
      visible: false,
      type: '',
    })
  }
  // 操作文件上传
  const inpRef = useRef(null)
  const fileChange = async (e) => {
    // console.log(e.target.files)
    const fd = new FormData()
    fd.append('photo', e.target.files[0])

    await dispatch(addFile(fd))
    onLeftClick()
  }
  // 定义性别头像数据
  const configList = {
    photo: [
      {
        title: '拍照',
        fn: () => {
          console.log('拍照')
        },
      },
      {
        title: '本地选择',
        fn: () => {
          inpRef.current.click()
        },
      },
    ],
    gender: [
      {
        title: '男',
        fn: () => {
          onCommit('gender', 0)
        },
      },
      {
        title: '女',
        fn: () => {
          onCommit('gender', 1)
        },
      },
    ],
  }
  // 修改生日
  const onBirthdayChange = (e) => {
    // 拿到生日表单数据，利用dayjs转换格式
    onCommit('birthday', dayjs(e).format('YYYY-MM-DD'))
  }
  // 退出登录逻辑
  const onLoginout = () => {
    Modal.alert('退出', '确认退出吗???', [
      {
        text: '取消',
      },
      {
        text: 'OK',
        onPress: () => {
          dispatch(loginOut())
          histroy.push('/login')
          Toast.success('退出成功')
        },
      },
    ])
   
  }
  useEffect(() => {
    dispatch(getUserEdit())
  }, [dispatch])
  const profile = useSelector((state) => state.profile.profile)
  // console.log(profile)
  const onCommit = (type, value) => {
    dispatch(
      editProfile({
        [type]: value,
      })
    )
    Toast.success('修改成功')
    onLeftClick()
  }
  return (
    <div className={styles.root}>
      <div className="content">
        {/* 顶部的导航栏 */}
        <NavBar>个人信息</NavBar>
        <div className="wrapper">
          <List className="profile-list">
            {/* 头像 */}
            <Item
              arrow="horizontal"
              onClick={() =>
                setListOpen({
                  visible: true,
                  type: 'photo',
                })
              }
              extra={
                <span className="avatar-wrapper">
                  <img src={profile.photo} alt="" />
                </span>
              }
            >
              头像
            </Item>
            {/* 昵称 */}
            <Item
              arrow="horizontal"
              extra={profile.name}
              onClick={() =>
                setOpen({
                  visible: true,
                  type: 'name',
                })
              }
            >
              昵称
            </Item>
            {/* 简介 */}
            <Item
              arrow="horizontal"
              extra={
                <span
                  className={classNames('intro', profile.intro ? 'normal' : '')}
                >
                  {profile.intro || '未填写'}
                </span>
              }
              onClick={() =>
                setOpen({
                  visible: true,
                  type: 'intro',
                })
              }
            >
              简介
            </Item>
          </List>

          <List className="profile-list">
            {/* 性别 */}
            <Item
              extra={profile.gender === 0 ? '男' : '女'}
              arrow="horizontal"
              onClick={() =>
                setListOpen({
                  visible: true,
                  type: 'gender',
                })
              }
            >
              性别
            </Item>
            {/* 生日 */}
            <DatePicker
              mode="date"
              value={new Date(profile.birthday)}
              onChange={onBirthdayChange}
              minDate={new Date('1900-01-01')}
              maxDate={new Date()}
              title="选择生日"
            >
              <Item arrow="horizontal" extra={'1998-06-06'}>
                生日
              </Item>
            </DatePicker>
          </List>
        </div>
        {/* 上传文件框 */}
        <input type="file" hidden onChange={fileChange} ref={inpRef} />
        {/* 底部栏：退出登录按钮 */}
        <div className="logout">
          <button onClick={onLoginout} className="btn">
            退出登录
          </button>
        </div>
      </div>

      {/* 抽屉组件 */}
      <Drawer
        className="drawer"
        style={{ minHeight: document.documentElement.clientHeight }}
        enableDragHandle
        contentStyle={{ color: '#A6A6A6', textAlign: 'center', paddingTop: 42 }}
        sidebar={
          open.visible && (
            <EditInput
              onCommit={onCommit}
              type={open.type}
              onLeftClick={onLeftClick}
            ></EditInput>
          )
        }
        open={open.visible}
      >
        11
      </Drawer>
      <Drawer
        className="drawer-list"
        open={listOpen.visible}
        onOpenChange={onLeftClick}
        position="bottom"
        sidebar={
          listOpen.visible && (
            <EditList
              onLeftClick={onLeftClick}
              type={listOpen.type}
              configList={configList}
            ></EditList>
          )
        }
      >
        11
      </Drawer>
    </div>
  )
}
